import pymongo
import gridfs
import hashlib

class PrebuiltDB():
    def __init__(self):
        self.conn = pymongo.Connection('localhost')
        self.gridfs = gridfs.GridFS(self.conn['test'], collection='foo')

        def get_orignal_file(path, revision):
            f = gridfs.get_last_version(path, revision=revision)
            
            if f is None:
                return None
            return f if f.length != 0 else gridfs.get(f.origid)

        def file_insert(path, revision):
            with open(path, 'rb') as f:
                fsfile = get_originala_file(path, revision=revision)
                if fsfile is None: # Not Exists
                    return gridfs.put(f, filename=path, revision=revision)
                else: # Exists
                    md5 = hashlib.md5()
                    for chunk in iter(lambda: f.read(128*md5.block_size), b''):
                        md5.update(chunk)
                    if fsfile.md5 != md5.hexdigest(): # but different
                        f.seek(0)
                        return gridfs.put(f, filename=path, revision=revision)
                    else: # and same
                        return gridfs.put('', filename=path, revision=revision, origid=fsfile._id)
